Olbrzymi zbiór ściąg odnoszących się do wszelkich programów oraz pakietów można znaleźć tutaj.
Platforma Anaconda powstała z myślą o obróbce danych. Składa się na nią wiele programów i bibliotek. Platforma jest stale rozwijana. Umożliwia pracę z językami programowania Python i R.
W przypadku, gdy ma się ograniczone zasoby pamięci można zainstalować okrojoną wersję platformy zwaną Miniconda Wtedy interesujące nas pakiety dołącza się za pomocą pakietu Conda służącego do zarządzania środowiskami, bibliotekami oraz zależnościami między pakietami. W miejsce Condy możemy też posługiwać się programem graficznym Anaconda Navigator (AN). Instaluje się on automatycznie w przypadku, gdy zdecydujemy się na pełną wesję Anacondy. Możemy też go doinstalować za pomocą Condy.
Użyteczne ściągi dotyczące Anacondy oraz Condy można znaleźć tutaj ściąga1 i tutaj ściąga2.
Będziemy posługiwali się głównie notatnikiem Jupyter Lab. Za jego pośrednictwem będziemy pisali i uruchamiali programy; wykonywali opisy i analizy.
Można też posługiwać się starszą wersją notatnika Jupyter Notebook a jeśli ktoś pisze dłuższy program, celowym jest użycie jakiegoś edytora; np. Atom, Notepad++, PyCharm lub wbudowany w dystrybucję Anaconda Spyder.
Jupyter wykorzystuje interaktywną powłokę IPython. Dzięki niej możemy na przemian kod pisać i natychmiast wykonywać. Pozwala to na zbudowanie nawet dużego programu poprzez niezależne testowanie małych fragmentów i składanie ich w całość. Jupyter umożliwia więcej: stworzenie całego interaktywnego dokumentu, gotowego do publikacji w sieci, czy odczytania za pomocą przeglądarki, w którym może się znaleźć tak tekst jak i wykresy, tabele, zdjęcia a nawet filmy.
Jest kilka sposobów uruchomienia Jupyter Lab (Notebook):
Ćwiczenie. Z notatnikami Jupyter można także pracować w ogóle nie instalując platformy Anaconda. Proszę się z tą możliwością zapoznać samodzielnie.
Witryna geeks for geeks poświęcona jest wszelkim aspektom analityki danych. Zawiera bogaty zasób treści dotyczących czystego Pythona, jego bibliotek oraz ich zastosowań. Jest napisana w języku angielskim, ale "googlowe" tłumaczenie na język polski jest całkiem przyzwoite.
Warto też zajrzeć na bloga Małgorzaty Łyczywek.
Obok Pythona znajdującego się w dystrybucji Anaconda bądź Miniconda, dobrze jest zainstalować najnowszą wersję Pythona ze strony programu. Program instalacyjny nie wymaga większej uwagi, jednak w trakcie instalacji można zaznaczyć okienko Add Python 3.9 to PATH. Dzięki temu będziemy mogli uruchamiać Pythona z wiersza poleceń lub terminala PowerShell. Tak zaleca w swojej książce Z. A. Shaw, jednak z pewnością nie jest to konieczne. Każdemu natomiast zaleca się przejrzenie znajdującego się w dokumentacji przewodnika po Pythonie - Python tutorial. W przewodniku omówione są zagadnienia niezbędne do posługiwania się Pythonem w analizie danych. Należy jeszcze zaznaczyć, że Pythona 3.9 nie da się zainstalować pod windows 7 lub jeszcze starszą wersją "okien". Wtedy trzeba zainstalować starszą wersję Pythona; np. 3.7.
Projekt Jupyter jest przedsięwzięciem, którego celem jest zbudowanie otwartego oprogramowania, otwartych standardów i usług służących interaktywnym obliczeniom z użyciem wielu języków programowania. Nazwa Jupyter jest skrótowcem utworzonym z trzech języków: Julia, Python, R (Ju-Pyt-eR).
Jupyter Lab ma trzy rodzaje okien, zwanych też komórkami: markdown, code, raw. W oknach markdown sporządzamy opisy, redagujemy treść. Okna code służą do pisania programów, zaś raw, do pisania tekstu nieobrobionego. Tekstem nieobrobionym możemy np. zapisać jakiś algorytm. Ten akapit zapisany jest w oknie markdown. Następny jest programem. Jeśli program chcemy wykonać, albo wyjść z trybu edycji do trybu podglądu, to klikamy myszą na okno i wciskamy kombinację klawiszy Shift+Enter.
for i in range(4):
print(i)
# drukujemy kwadraty pierwszych pięciu liczb naturalnych
# począwszy od 0
for i in range(5):
print(i**2)
Następne okno zapisane jest w formacie raw.
Zauważmy, że okna markdown i raw są nienumerowane, zaś code i owszem. Dlaczego?
2+2 # dodałem dwie liczby
3*4 # pomnożyłem
320/133 # podzieliłem
# A teraz wykonam skomplikowaną operację:
((3-7)/(4+2)-((3+1)/(16+7)+((3/7)/19)/20 +1))*34
$(\frac{3-7}{4+2}-(\frac{3+1}{16+7}+\frac {\frac{\frac 3 7} {19}}{20} +1)) \cdot 34$
(-4/6-(4/23 +(3/(19*140)+1)))*34
# Jeszcze mogę potęgować:
2**(1/3)
# A teraz dwie operacje na liczbach całkowitych:
33//7, 23%4
$m\% k$ oznacza więc resztę z dzielenia $m$ przez $k$, zaś $m//k$ oznacza wynik z dzielenia z resztą $m$ przez $k$ z pominięciem reszty.
type(3), type(3.5), type(4/10), type(10//4)
x=2.5
y=22.3
z=x*y
z
z**2
z**3
print(z**2)
print(z**3)
z**2, z**3
z = z**2
ćma=z
ćma
x == y
x <= y
x > y
Liczby zespolone zapisujemy w Pythonie tak: $a+bj$.
(0.5+1j)*(3j)
(0.5+1j)*3*(0.5-1j)
Możemy też zapisywać je w formie: $\tt complex(a,b)$
complex(2,3)*complex(2,-3)
type(j)
type(1j)
s=1.5+2j
s.real, s.imag, abs(s)
(1.5**2+2.0**2)**0.5
Dowolne ciągi znaków Unicode wydzielone za pomocą cudzysłowów ' ' bądź " ".
# Przykład
'Wart Pac pałaca, a pałac Paca.'
"Wart Pac pałaca, a pałac Paca."
"Wart Pac pałaca, a 'pałac' Paca."
'ala',' ','ma kota'
ala = 'Ala'
3 * ala
ala = 'Ala '
3 * ala
ala*2
ala**2
type(ala)
pac= 'Wart Pac pałaca, a pałac Paca.'
kac='Ma kaca Pac i Pac ma kaca.'
pac+kac #dodawanie łańcuchów zwane inaczej konkatenacją albo zestawianiem
str([1,2,3,4,5])
str(123)
len(kac) #funkcja len liczy ile jest znaków w łańcuchu (length - ang. długość)
len(kac+pac)
kac
kac[3:19] #podsłowo, począwszy od litery o numerze 3 (to będzie czwarta, bo zaczynamy od 0),
#do litery o numerze 18.
'Schizofrenia'[2:6]
kac[5:-7]
mac = kac
mac==kac #pytanie o równość; czy łancuchy mac i kac są takie same
mac = mac+' Tralabomba' #zmiana wartości zmiennej mac (czy takze kac ?)
mac==kac #powtórne pytanie o równość
mac!=kac #pytanie o różność!
gracz='Chanel No 5'
pracz=gracz
print(pracz==gracz)
pracz = pracz +' Tralabomba'
pracz==gracz
help(str)
Help on class str in module builtins: class str(object) | str(object='') -> str | str(bytes_or_buffer[, encoding[, errors]]) -> str | | Create a new string object from the given object. If encoding or | errors is specified, then the object must expose a data buffer | that will be decoded using the given encoding and error handler. | Otherwise, returns the result of object.__str__() (if defined) | or repr(object). | encoding defaults to sys.getdefaultencoding(). | errors defaults to 'strict'. | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return key in self. | | __eq__(self, value, /) | Return self==value. | | __format__(self, format_spec, /) | Return a formatted version of the string as described by format_spec. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(self, key, /) | Return self[key]. | | __getnewargs__(...) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __mod__(self, value, /) | Return self%value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __repr__(self, /) | Return repr(self). | | __rmod__(self, value, /) | Return value%self. | | __rmul__(self, value, /) | Return value*self. | | __sizeof__(self, /) | Return the size of the string in memory, in bytes. | | __str__(self, /) | Return str(self). | | capitalize(self, /) | Return a capitalized version of the string. | | More specifically, make the first character have upper case and the rest lower | case. | | casefold(self, /) | Return a version of the string suitable for caseless comparisons. | | center(self, width, fillchar=' ', /) | Return a centered string of length width. | | Padding is done using the specified fill character (default is a space). | | count(...) | S.count(sub[, start[, end]]) -> int | | Return the number of non-overlapping occurrences of substring sub in | string S[start:end]. Optional arguments start and end are | interpreted as in slice notation. | | encode(self, /, encoding='utf-8', errors='strict') | Encode the string using the codec registered for encoding. | | encoding | The encoding in which to encode the string. | errors | The error handling scheme to use for encoding errors. | The default is 'strict' meaning that encoding errors raise a | UnicodeEncodeError. Other possible values are 'ignore', 'replace' and | 'xmlcharrefreplace' as well as any other name registered with | codecs.register_error that can handle UnicodeEncodeErrors. | | endswith(...) | S.endswith(suffix[, start[, end]]) -> bool | | Return True if S ends with the specified suffix, False otherwise. | With optional start, test S beginning at that position. | With optional end, stop comparing S at that position. | suffix can also be a tuple of strings to try. | | expandtabs(self, /, tabsize=8) | Return a copy where all tab characters are expanded using spaces. | | If tabsize is not given, a tab size of 8 characters is assumed. | | find(...) | S.find(sub[, start[, end]]) -> int | | Return the lowest index in S where substring sub is found, | such that sub is contained within S[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Return -1 on failure. | | format(...) | S.format(*args, **kwargs) -> str | | Return a formatted version of S, using substitutions from args and kwargs. | The substitutions are identified by braces ('{' and '}'). | | format_map(...) | S.format_map(mapping) -> str | | Return a formatted version of S, using substitutions from mapping. | The substitutions are identified by braces ('{' and '}'). | | index(...) | S.index(sub[, start[, end]]) -> int | | Return the lowest index in S where substring sub is found, | such that sub is contained within S[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Raises ValueError when the substring is not found. | | isalnum(self, /) | Return True if the string is an alpha-numeric string, False otherwise. | | A string is alpha-numeric if all characters in the string are alpha-numeric and | there is at least one character in the string. | | isalpha(self, /) | Return True if the string is an alphabetic string, False otherwise. | | A string is alphabetic if all characters in the string are alphabetic and there | is at least one character in the string. | | isascii(self, /) | Return True if all characters in the string are ASCII, False otherwise. | | ASCII characters have code points in the range U+0000-U+007F. | Empty string is ASCII too. | | isdecimal(self, /) | Return True if the string is a decimal string, False otherwise. | | A string is a decimal string if all characters in the string are decimal and | there is at least one character in the string. | | isdigit(self, /) | Return True if the string is a digit string, False otherwise. | | A string is a digit string if all characters in the string are digits and there | is at least one character in the string. | | isidentifier(self, /) | Return True if the string is a valid Python identifier, False otherwise. | | Call keyword.iskeyword(s) to test whether string s is a reserved identifier, | such as "def" or "class". | | islower(self, /) | Return True if the string is a lowercase string, False otherwise. | | A string is lowercase if all cased characters in the string are lowercase and | there is at least one cased character in the string. | | isnumeric(self, /) | Return True if the string is a numeric string, False otherwise. | | A string is numeric if all characters in the string are numeric and there is at | least one character in the string. | | isprintable(self, /) | Return True if the string is printable, False otherwise. | | A string is printable if all of its characters are considered printable in | repr() or if it is empty. | | isspace(self, /) | Return True if the string is a whitespace string, False otherwise. | | A string is whitespace if all characters in the string are whitespace and there | is at least one character in the string. | | istitle(self, /) | Return True if the string is a title-cased string, False otherwise. | | In a title-cased string, upper- and title-case characters may only | follow uncased characters and lowercase characters only cased ones. | | isupper(self, /) | Return True if the string is an uppercase string, False otherwise. | | A string is uppercase if all cased characters in the string are uppercase and | there is at least one cased character in the string. | | join(self, iterable, /) | Concatenate any number of strings. | | The string whose method is called is inserted in between each given string. | The result is returned as a new string. | | Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs' | | ljust(self, width, fillchar=' ', /) | Return a left-justified string of length width. | | Padding is done using the specified fill character (default is a space). | | lower(self, /) | Return a copy of the string converted to lowercase. | | lstrip(self, chars=None, /) | Return a copy of the string with leading whitespace removed. | | If chars is given and not None, remove characters in chars instead. | | partition(self, sep, /) | Partition the string into three parts using the given separator. | | This will search for the separator in the string. If the separator is found, | returns a 3-tuple containing the part before the separator, the separator | itself, and the part after it. | | If the separator is not found, returns a 3-tuple containing the original string | and two empty strings. | | replace(self, old, new, count=-1, /) | Return a copy with all occurrences of substring old replaced by new. | | count | Maximum number of occurrences to replace. | -1 (the default value) means replace all occurrences. | | If the optional argument count is given, only the first count occurrences are | replaced. | | rfind(...) | S.rfind(sub[, start[, end]]) -> int | | Return the highest index in S where substring sub is found, | such that sub is contained within S[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Return -1 on failure. | | rindex(...) | S.rindex(sub[, start[, end]]) -> int | | Return the highest index in S where substring sub is found, | such that sub is contained within S[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Raises ValueError when the substring is not found. | | rjust(self, width, fillchar=' ', /) | Return a right-justified string of length width. | | Padding is done using the specified fill character (default is a space). | | rpartition(self, sep, /) | Partition the string into three parts using the given separator. | | This will search for the separator in the string, starting at the end. If | the separator is found, returns a 3-tuple containing the part before the | separator, the separator itself, and the part after it. | | If the separator is not found, returns a 3-tuple containing two empty strings | and the original string. | | rsplit(self, /, sep=None, maxsplit=-1) | Return a list of the words in the string, using sep as the delimiter string. | | sep | The delimiter according which to split the string. | None (the default value) means split according to any whitespace, | and discard empty strings from the result. | maxsplit | Maximum number of splits to do. | -1 (the default value) means no limit. | | Splits are done starting at the end of the string and working to the front. | | rstrip(self, chars=None, /) | Return a copy of the string with trailing whitespace removed. | | If chars is given and not None, remove characters in chars instead. | | split(self, /, sep=None, maxsplit=-1) | Return a list of the words in the string, using sep as the delimiter string. | | sep | The delimiter according which to split the string. | None (the default value) means split according to any whitespace, | and discard empty strings from the result. | maxsplit | Maximum number of splits to do. | -1 (the default value) means no limit. | | splitlines(self, /, keepends=False) | Return a list of the lines in the string, breaking at line boundaries. | | Line breaks are not included in the resulting list unless keepends is given and | true. | | startswith(...) | S.startswith(prefix[, start[, end]]) -> bool | | Return True if S starts with the specified prefix, False otherwise. | With optional start, test S beginning at that position. | With optional end, stop comparing S at that position. | prefix can also be a tuple of strings to try. | | strip(self, chars=None, /) | Return a copy of the string with leading and trailing whitespace removed. | | If chars is given and not None, remove characters in chars instead. | | swapcase(self, /) | Convert uppercase characters to lowercase and lowercase characters to uppercase. | | title(self, /) | Return a version of the string where each word is titlecased. | | More specifically, words start with uppercased characters and all remaining | cased characters have lower case. | | translate(self, table, /) | Replace each character in the string using the given translation table. | | table | Translation table, which must be a mapping of Unicode ordinals to | Unicode ordinals, strings, or None. | | The table must implement lookup/indexing via __getitem__, for instance a | dictionary or list. If this operation raises LookupError, the character is | left untouched. Characters mapped to None are deleted. | | upper(self, /) | Return a copy of the string converted to uppercase. | | zfill(self, width, /) | Pad a numeric string with zeros on the left, to fill a field of the given width. | | The string is never truncated. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | maketrans(...) | Return a translation table usable for str.translate(). | | If there is only one argument, it must be a dictionary mapping Unicode | ordinals (integers) or characters to Unicode ordinals, strings or None. | Character keys will be then converted to ordinals. | If there are two arguments, they must be strings of equal length, and | in the resulting dictionary, each character in x will be mapped to the | character at the same position in y. If there is a third argument, it | must be a string, whose characters will be mapped to None in the result.
help(str)
ddd='isafdrga'
ddd.islower()
mac, kac
mac.capitalize()
mac
mac.upper()
mac.lower()
mac.upper()+mac.lower()
mac.partition('Pac ma ')
mac.replace('Pac', 'Bach')
Listy to podstawowy sposób organizacji danych (struktura danych) w Pythonie.
[1,2,3,4,'a', [1,2,[3]]] #przyład
Jak widać, lista może zawierać liczby, łańcuchy a także inne listy (może być zagnieżdżona).
x, y=[1,2,3], [31,31,33]
z=x+y
z
2*z
z*2
z*z
print((2*x+3*y)*5)
[1,2,3]+[]
[[[],[]],[[]],[]]
print(z)
len(z)
z[2], z[3]
z[6]
z[1:4]
z[:4]
z[3:]
z[3:10]
v=[[1,2,'a'],[4,5,6],[7,8,9],[10,11,12]]
v[2]
v[2][1]
u=[]
for x in v:
for y in x:
u.append(y) # u=u+[y], u+=[y]
u
Ćwiczenie. Sporządź listę kwadratów pierwszych stu liczb naturalnych (zaczynamy od 0!).
Rozwiązanie. Instrukcja wygląda podobnie jak w przypadku zbiorów: $K=\{x^2\colon x\in\{0,\ldots, 99\}\}$. Jednak zamiast $\{0,\ldots, 99\}$ w Pythonie piszemy: $\texttt{range(100)}$; zamiast $x^2\colon x\in$, w Pythonie piszemy: $\texttt{x**2 for x in}$. Otrzymamy
K=[x**2 for x in range(100)]
# Nam chodzi o listę, a nie o zbiór, więc zapisujemy w nawiasach kwadratowych.
print(K)
Gdybyśmy mieli życzenie sporządzić listę trzydziestu kolejnych kwadratów począwszy od kwadratu liczby 7, to musielibyśmy zmienić iterator na $\texttt{range(7, 37)}$:
[x**2 for x in range(7, 37)]
Ćwiczenie. Sporządź listę $L$ kwadratów liczb nieparzystych nieprzekraczających 100.
Rozwiązanie. Zbiór takich liczb moglibyśmy określilić tak: $L=\{x^2\colon x\in \{0,\ldots, 100\}, \text{o ile $x$ jest nieparzysta}\}$. W Pythonie zrobimy to bardzo podobnie:
L=[x**2 for x in range(101) if x%2==1]
#liczby nieparzyste to te, których reszta z dzielenia przez 2 daje 1
L
Opisaną procedurę nazywamy filtrowaniem: dopisaliśmy warunek, który $x$ musi spełniać (ma być nieparzysty) by element, w tym wypadku $x^2$, był zaliczony do $L$.
print(L)
345%2==1, 344%2==1, 344%2==0
Instrukcja to polecenie przekształcenia jakichś danych, często przechowywanych w postaci listy, łańcucha itp. Jeśli sposób wykonania przekształcenia zależy od dodatkowych warunków, to mówimy o instrukcji warunkowej. W Pythonie zarezerwowano odpowiednie słowa służące do tworzenia takich instrukcji, np.: $\texttt{if, elif, else}$.
wiek=input()
wiek
wiek=input('Ile masz lat? ')
wzrost=input('Ile mierzysz? ')
waga=input('Ile ważysz?')
if int(wiek) >= 45:
print("Jak zuważyłeś, nazwa naszej placówki to 'Klinika Młodych'. Ludzi w Twoim wieku nie przyjmujemy.")
elif int(wzrost)>185:
print("Skąd mamy wziąć łóżko odpowiednie do Twojego wzrostu. Szukaj innego miejsca.")
elif int(waga)>45:
print("Obawiamy się, że nasze racje żywnościowe mogą nie być dla Ciebie wystarczające. Musiałbyś odżywiać się we własnym zakresie.")
else:
print("Proszę o stawienie się w naszym zakładzie za dwa tygodnie")
wiek=input('Ile masz lat? ')
wzrost=input('Ile mierzysz? ')
waga=input('Ile ważysz?')
if int(wiek) >= 45:
print("Jak zuważyłeś, nazwa naszej placówki to 'Klinika Młodych'. Ludzi w Twoim wieku nie przyjmujemy.")
elif int(wzrost)>185:
print("Skąd mamy wziąć łóżko odpowiednie do Twojego wzrostu. Szukaj innego miejsca.")
if int(waga)>45:
print("Obawiamy się, że nasze racje żywnościowe mogą nie być dla Ciebie wystarczające. Musiałbyś odżywiać się we własnym zakresie.")
else:
print("Proszę o stawienie się w naszym zakładzie za dwa tygodnie")
Instrukcji tej użyliśmy kilkukrotnie. Za każdym razem odwoływaliśmy się do iteratorów $\texttt{range}$. Można także wykonywać tę instrukcję na każdym ciągu jak łańcuch, czy lista.
Przykład użycia $\texttt{for}$ na łańcuchu.
w='abcdefghijklmnopqrstuvwxyz'
i=0
for x in w:
print(x, i)
i=i+1
Przykład użycia instrukcji $\texttt{for}$ na liście.
v=[[1,2],[4,5],[9,10]]
V=[]
for x in v:
V=V+x
V
Iterator $\texttt{range}$ może być także użyty z określonym skokiem: $\texttt{range(m,n, s)}$. Liczba startowa $m$ kolejne $m+s$, $m+2s$, itd. Ostatnia liczba w ciągu jest mniejsza niż $n$ i zarazem największą postaci $m+ks$.
for i in range(-4, 11, 3):
print(i)
range(-4,11,3) # Obiekt range nie zajmuje pamięci, jak np. lista.
list(range(-4,11,3)) # Funkcja list(x) tworzy z obiektu x listę, o ile to możliwe.
list('abcdef')
i=-4 #porównaj z range(-4,11,3)
while i<11:
print(i)
i=i+3
Ćwiczenie Dwa pierwsze wyrazy ciągu F.: 1, 1. Kolejne są sumami dwu poprzedzających. Wyznacz pierwsze trzydzieści wyrazów tego ciągu.
Rozwiązanie.
x=[1] #wyrazy zbierzemy na liście x
a=1
b=1
i=0
while i<=28:
[a,b]=[b,a+b]
x=x+[a]
i=i+1
#Sprawdzenie:
print(len(x))
print(x)
Listy, podobnie jak łańcuchy i inne klasy mają swoje swoje metody. Można je wywołać:
help(list)
Można też zajrzeć do podrozdziału 5.1 Poradnika (Tutorial).
Listy są obiektami mutowalnymi, tzn. możemy zmieniać zawartość listy tak jak zmieniamy wartość zmiennej, pozostawiając jej nazwę
L=[7,2,3,'a', 8,9]
L[3]=2
L
L[2:5]=[328]
L
L[5]=2
L.append(4)
L
L.pop()
L
Ćwiczenie. Dane:
A=[[1],2,[3]]
B='stek'
Jaki będzie rezultat wykonania następujących instrukcji? W szczególności, czy listy Cytata i A będą różne, czy takie same?
Cytata=A
A.append(B)
print(A)
print(Cytata)
I odrobinę więcej komplikacji. Jak będzie wyglądała lista P powstała w wyniku zastosowania kolejnych operacji?
x=[1,2,3,4]
P=[x for i in range(7)]
P[3][3]='zdziwiony?'
x, P
Wniosek $P$ jest listą tożsamych list. Zmiana jednej, wywołuje identyczną zmianę pozostałych. $P[3]$ jest inną etykietą (aliasem) listy $x$.
Jeśli chcemy, by listy były identyczne lecz nietożsame, musimy sporządzić ich (płytkie) kopie:
x=[1,2,3,4]
R=[x.copy() for i in range(7)]
R[3][3]='niezdziwiony'
R
(proszę przeszukać dokumentację lub dostępne podręczniki w celu uzyskania dodatkowych informacji)
Ćwiczenie. Sprawdzić, czy na liście znajduje się pozycja 'czerwony' i wydrukować komunikat.
magazyn=[1,2,3,4,'biały',1,13,'czerwony', 'niebieski', 'buk', 'leń', 'czerwony', 23, 14, 'XXXX', 'czerwony', 'pp','biały']
for x in magazyn:
if x=='czerwony':
print("Na magazynie znajduje się 'czerwony'")
for x in magazyn:
if x=='czerwony':
print("Na magazynie znajduje się 'czerwony'")
break
Ćwiczenie. Wykonać poniższą instrukcję. Następnie wyłączyć linię continue i wykonać:
for num in range(13):
if num%2==0:
print("Znaleziono liczbę parzystą", num)
continue
print("Znaleziono liczbę", num)
I jeszcze podobne:
Ćwiczenie. Wykonać poniższą instrukcję zmieniając dowolnie wartość zmiennej $x$.
x="atoli"
try:
print(x%2)
except:
print('x nie jest liczbą całkowitą')
Jeśli jakiś fragment programu powtarza się, a zmieniają się jedynie dane, warto stworzyć funkcję, która będzie obsługiwała wszystkie takie przypadki. Tym samym będziemy mogli wielokrotnie wykorzystać ten sam fragment kodu.
Przykład. Chcemy wyznaczyć wszystkie ciągi 0-1 długości 7. Wtedy lepiej napisać funkcję pozwalającą na wyznaczenie wszystkich ciągów długości $n\ge 1$.
def zerojeden(n):
x=[[]]
for i in range(n):
x=[[0]+u for u in x]+[[1]+ u for u in x]
return(x)
$\texttt{return(x)}$ oznacza, że wywołanie funkcji $\texttt{zerojeden(n)}$ tworzy listę $x$ złożoną ze wszystkich ciągów 0-1 długości $n$. Oczywiście $n$ musi mieć konkretną wartość. Lista ta jest drukowana automatycznie:
zerojeden(3)
Jeśli chcemy drukowania uniknąć, musimy nadać liście etykietę:
z3=zerojeden(3)
Ćwiczenie. Ciąg Fibonacciego może startować z jakiejkolwiek pary wartości $a$, $b$. Określ funkcję wyznaczającą pierwszych $n$ wyrazów ciągu Fibonacciego o wyrazach początkowych $a$, $b$.
def fib(a,b, n):
L=[a]
for i in range(n-1):
a, b=b, a+b
L.append(a)
return(L)
fib(2,-1,10)
Jeśli jakieś wartości startowe będą używane najczęściej, możemy argumenty startowe zdeklarować z domyślnymi wartościami. Wtedy będziemy mogli je pominąć przy wywoływaniu funkcji.
def fib2(n, a=1,b=1):
L=[a]
for i in range(n-1):
a, b=b, a+b
L.append(a)
return(L)
fib2(10,2,-1)
Proszę zwrócić uwagę na zmianę kolejności argumentów. Argumenty o wartościach domyślnych deklarujemy zawsze na końcu.
fib2(8)
fib2(10,2,-1)
Za argumentami funkcji mogą się kryć dowolne dane, także listy, łańcuchy bądź krotki.
Krotki są podobne to list, jednak są niemutowalne. To znaczy, nie możemy ich traktować jak zmiennej przechowującej ciąg danych, które możemy niezależnie aktualizować, tak jak czynimy to w przypadku listy.
x=(1,2,3,4,5)
y=[1,2,3,4,5]
y[3]='a co tam'
y
# lista y uległ modyfkacji
# to samo dla x
x[3]='a co tam'
# Listy i krotki można zamieniać jedne w drugie za pomocą wbudowanych funkcji list(),
# tuple():
list(x), tuple(list(x))
# Skoro krotki są niemutowalne, to czy mogą zawierać mutowalne elementy?
([1],[2,[3]], 35)
Więcej na temat krotek w dokumentacji. Metody możemy poznać za pomocą $\texttt{help(tuple)}$.
tuple?
Ćwiczenie. Zbudować funkcję, która przeplata wyrazy dwu list. Listy powinny być równej długości, a jeśli nie są, to powinniśmy otrzymać stosowny komunikat.
def przeplatacz(u,v):
a,b=len(u), len(v)
if a!=b: #obsługa wyjątków
print('Dane mają niezgodny format.')
else:
L=[]
for i in range(a):
L.append(u[i])
L.append(v[i])
return L
u,v=[1,2,3], ['a','b','c']
L=przeplatacz(u,v)
L
v=tuple(v)
L=przeplatacz(u,v)
L
przeplatacz('Bigda','Dyzma')
Komentarz. Jak widać, jeśli typy danych nie są w definicji funkcji zadeklarowane, to można użyć innych typów niż te, dla których funkcję domyślnie tworzyliśmy. W wielu językach np. Pascal, C, niepodobna określić funkcji bez wyraźnego określenia typu zmiennych.